#include <muduo/net/TcpServer.h>
#include <muduo/net/TcpClient.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/Buffer.h>
#include <iostream>
#include <unordered_map>
#include <functional>
#include <string>
using namespace std;

class DictClient
{
private:
    muduo::net::TcpConnectionPtr _conn;
    muduo::CountDownLatch _cd;
    muduo::net::EventLoopThread _loopthread;  //实例化好，内部自动循环监控，不需要手动写。
    muduo::net::EventLoop* _baseloop;
    muduo::net::TcpClient _client;
    
public:
    DictClient(string sip,int sport)
    :_client(_baseloop,muduo::net::InetAddress(sip,sport),"DictClient")
    ,_baseloop(_loopthread.startLoop()) //实例化好
    ,_cd(1) //初始化为1，因为到0时会唤醒
    {
        //调用我写的回调
        _client.setConnectionCallback(bind(&DictClient::onConnection,this,placeholders::_1));
        _client.setMessageCallback(bind(&DictClient::onMessageConn,this,placeholders::_1,placeholders::_2,placeholders::_3));
        
        _client.connect(); //非阻塞接口
        _cd.wait();
    }

    bool send(const string& s)
    {
        if(_conn->connected() == false)
        {
            cout << "连接断开，发送数据失败" << endl;
            return false;
        }
        _conn->send(s);
        return true;
    }
private:
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            cout << "连接成功！" << endl;
            _cd.countDown(); //计数--，为0就阻塞
            //赋给_conn去进行send
            _conn = conn;
        }
        else
        {
            cout << "连接失败" << endl;
            _conn.reset();
        }
    }

    void onMessageConn(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buff,muduo::Timestamp receiveTime)
    {
       string ret = buff->retrieveAllAsString();
       cout << ret << endl;
    }
};


int main()
{
    DictClient dictclient("127.0.0.1",8888);
    string s;
    while(getline(cin,s))
        dictclient.send(s);
    return 0;
}